package com.acknight.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.acknight.constant.PhoneConstant;
import com.acknight.constant.RedisConstants;
import com.acknight.constant.UserConstant;
import com.acknight.dto.LoginFormDTO;
import com.acknight.dto.Result;
import com.acknight.dto.UserDTO;
import com.acknight.entity.UserInfo;
import com.acknight.service.IUserInfoService;
import com.acknight.utils.BeanCopyUtils;
import com.acknight.utils.RegexUtils;
import com.acknight.utils.UserHolder;
import com.acknight.vo.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.acknight.entity.User;
import com.acknight.mapper.UserMapper;
import com.acknight.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.acknight.constant.RedisConstants.USER_SIGN_KEY;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private IUserInfoService userInfoService;

    /**
     * 实现登录功能
     * @param loginForm
     * @return
     */
    @Override
    public Result login(LoginFormDTO loginForm) {
        // 1.效验手机号
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)) {
            // 2.如果不符合，返回错误信息
            return Result.fail("手机号格式错误!");
        }


        // 3.一致，根据手机号查询用户
        User user = query().eq(PhoneConstant.PHONE, phone).one();

        if (user == null || user.getIsDelete().equals(1)) {
            return Result.fail("用户不存在!");
        }

        String salt = user.getSalt();

        String md5Password = getMD5Password(loginForm.getPassword(), salt);

        // 4.判断用户是否存在


        if (!user.getPassword().equals(md5Password)) {
            return Result.fail("密码错误，请重新输入!");
        }

        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getUserId, user.getId());

        UserInfo userInfo = userInfoService.getOne(queryWrapper);
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(userInfo, UserInfoVo.class);
        userInfoVo.setIcon(user.getIcon());
        userInfoVo.setNickName(user.getNickName());
        userInfoVo.setPhone(user.getPhone());
        userInfoVo.setCreateTime(user.getCreateTime());

        return Result.ok(userInfoVo);
    }

    /**
     * 定义一个md5加密处理
     * @return
     */
    private String getMD5Password(String password, String salt) {

        for (int i = 0; i < 3; i++) {
            // md5加密算法方法的调用
           password = DigestUtils.md5DigestAsHex((salt + password + salt).getBytes()).toUpperCase();
        }
        // 返回加密之后的password
        return password;
    }

    @Override
    public Result logout() {
        return Result.ok();
    }

    @Override
    public Result me(Integer userId) {
        User user = getById(userId);
        UserInfo userInfo = userInfoService.getById(userId);
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(userInfo, UserInfoVo.class);

        userInfoVo.setUserId(user.getId());
        userInfoVo.setIcon(user.getIcon());
        userInfoVo.setNickName(user.getNickName());
        userInfoVo.setPhone(user.getPhone());
        userInfoVo.setCreateTime(user.getCreateTime());

        return Result.ok(userInfoVo);
    }

    @Override
    public Result register(LoginFormDTO loginForm) {
        // 1.效验手机号
        String phone = loginForm.getPhone();

        if (RegexUtils.isPhoneInvalid(phone)) {
            // 2.如果不符合，返回错误信息
            return Result.fail("手机号格式错误!");
        }

        String salt = UUID.randomUUID().toString().toUpperCase();

        String md5Password = getMD5Password(loginForm.getPassword(), salt);

        User user = query().eq(PhoneConstant.PHONE, phone).one();

        // 判断用户是否存在
        if (user != null) {
            return Result.fail("用户已存在!");
        }

        user = new User().setPhone(phone).setPassword(md5Password).setSalt(salt);

        save(user);

        return Result.ok(user);
    }

    @Override
    public Result infoSave(UserInfoVo userInfoVo) {
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getUserId, userInfoVo.getUserId());
        UserInfo userInfo = userInfoService.getOne(queryWrapper);
        User user = getById(userInfo.getUserId());
        if (userInfo != null) {
            if (!userInfoVo.getNickName().equals(user.getNickName())) {
                user.setNickName(userInfoVo.getNickName());
            }
            if (!userInfoVo.getIntroduce().equals("") && !userInfoVo.getIntroduce().equals(userInfo.getIntroduce())) {
                userInfo.setIntroduce(userInfoVo.getIntroduce());
            }
            if (!userInfoVo.getCity().equals("") && !userInfo.getCity().equals(userInfoVo.getCity())) {
                userInfo.setCity(userInfoVo.getCity());
            }
            if (userInfoVo.getGender() != null && !userInfo.getGender().equals(userInfoVo.getGender())) {
                userInfo.setGender(userInfoVo.getGender());
            }
            userInfoService.update(userInfo, queryWrapper);
        } else {
            userInfo = new UserInfo();
            userInfo.setUserId(userInfoVo.getUserId());
            userInfo.setCity(userInfoVo.getCity());
            userInfo.setGender(userInfoVo.getGender());
            userInfo.setIntroduce(userInfoVo.getIntroduce());

            userInfoService.save(userInfo);
        }
        if (!userInfoVo.getIcon().equals("") && !userInfoVo.getIcon().equals(user.getIcon())) {
            user.setIcon(userInfoVo.getIcon());
            updateById(user);
        }
        UserInfoVo userInfoVoResult = BeanCopyUtils.copyBean(userInfo, UserInfoVo.class);
        userInfoVoResult.setIcon(user.getIcon());
        userInfoVoResult.setNickName(user.getNickName());
        userInfoVoResult.setPhone(user.getPhone());
        userInfoVoResult.setCreateTime(user.getCreateTime());
        return Result.ok(userInfoVoResult);
    }
}
